<?php

namespace app\service;

use app\common\BaseService;
use app\model\OuterPurchase as OuterPurchaseModel;
use think\facade\Db;

class OuterPurchaseService extends BaseService
{
  public static function getInstance(): OuterPurchaseService
  {
    return parent::getInstance();
  }

  public static function getModel(): OuterPurchaseModel
  {
    return OuterPurchaseModel::getInstance();
  }

  public static function getDataByCondition($conditions) {
    return self::getModel()->getDataByCondition($conditions);
  }

  public function getOuterJoinStore($conditions) {
    $query = Db::name('outer_purchase')
      ->alias('o')
      ->field('o.*, s.base, s.name, s.unit, s.category_id, c.category_name, u.basename')
      ->join('store_house s', 's.id = o.store_id', 'LEFT')
      ->join('category c', 's.category_id = c.id', 'LEFT')
      ->join('user u', 's.base = u.base', 'LEFT');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order('s.id', 'DESC');
    return $query->select()->toArray();
  }

  /*
   * 门店批量外部采购
   */
  public static function createMultiOuter($base, $data, $sure=false) {
    // 新增到outer_purchase
    $insertOuter = [];
    // 更新到store_house
    $updateHouse = [];
    // 新增到store_house
    $insertHouse = [];
    // 获取商品表中含有的数据
    $names = array_column($data, 'name');
    $outerList = GoodsService::getInstance()->getGoodsHouse([['g.sale_name',$names, 'IN']]);
    $outerList = array_column($outerList,null, 'sale_name');
    // 获取门店仓库数据
    $storeHouse = StoreService::getModel()->getDataByCondition([ ['name', $names, 'IN'], ['status', 1, '='], ['base', $base, '='] ]);
    $storeHouse = array_column($storeHouse, null, 'name');
    // 获取保存分类
    $categoryList = [];
    $storeCat = CategoryService::getInstance()->getCategoryByCondition([['base', $base, '=']]);
    $storeCat = array_column($storeCat, 'id', 'category_name');
    $houseCat = CategoryService::getInstance()->getCategoryByCondition([['base', 0, '=']]);
    $houseCat = array_column($houseCat, 'category_name', 'id');
    foreach ($houseCat as $ck => $cv) {
      if (isset($storeCat[$cv])) {
        $categoryList[$ck] = $storeCat[$cv];
      }
    }

    // 获取采购单号
    $cond = [
      ['insert_time', date('Y-m-d'), '>=']
    ];
    $outer = self::getModel()->getDataByCondition($cond);
    $arr = array_unique(array_column($outer, 'sell_number'));
    $num = str_pad(count($arr) + 1, 3, '0',STR_PAD_LEFT);
    $sellNumber = 'WB'.date('Ymd').$num;
    if ($outerList && !$sure) {
      $msg = "确认采购商品是否与门店的以下商品为同一品类，如不一致 请修改商品名称，反之则按一下商品录入：<br>";
      foreach ($outerList as $key => $ov) {
        $msg .= $key."：该商品分类为 ‘".$ov['category_name']."’，单位为 ‘".$ov['unit'].'’ <br>';
      }
      return ['status' => true, 'msg' => $msg];
    }
    foreach ($data as $v) {
      $outer = [];
      $goods_id = null;
      $unit = $v['unit'];
      $category_id = $v['category_id'];
      // 查看是否是商品表数据
      if (isset($outerList[$v['name']])) {
        $outer = $outerList[$v['name']];
        $goods_id = $outer['id'];
        $unit = $outerList[$v['name']]['unit'];
        if (!isset($categoryList[$outerList[$v['name']]['category_id']])) {
          return ['status' => false, 'msg' => '该门店暂无分类：'.$outerList[$v['name']]['category_name']];
        }
        $category_id = $categoryList[$outerList[$v['name']]['category_id']];
      }
      if ($base === '') {
        return ['status' => false, 'msg' => '请选择流向'];
      }
      $insertOuter[$v['name']] = [
        'sell_number' => $sellNumber,
        'store_id' => isset($storeHouse[$v['name']]) ? $storeHouse[$v['name']]['id'] : '',
        'price' => $v['price'],
        'count' => $v['count'],
        'comment' => $v['comment'],
        'purchase_time' => $v['purchase_time'],
        'status' => 1,
        'insert_time' => date('Y-m-d H:i:s'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];

      // 是否已有数据
      if (isset($storeHouse[$v['name']])) {
        $house = $storeHouse[$v['name']];
        $total = $house['total_amount'] + ($v['count']*$v['price']);
        $updateHouse[] = [
          'id' => $house['id'],
          'count' => $house['count'] + $v['count'],
          'total_amount' => $total,
          'price' => round($total/($house['count'] + $v['count']), 2)
        ];
      } else {
        $insertHouse[] = [
          'goods_id' => $goods_id ? $goods_id : null,
          'category_id' => isset($category_id) ? $category_id : null,
          'name' => $v['name'],
          'price' => $v['price'],
          'count' => $v['count'],
          'unit' => $unit,
          'total_amount' => round($v['price'] * $v['count'], 2),
          'base' => $base,
          'status' => 1,
          'insert_time' => date('Y-m-d H:i:s'),
          'last_update_time' => date('Y-m-d H:i:s')
        ];
      }
    }
    self::getModel()->startTrans();
    try {
      // 更新到store_house
      if ($updateHouse) {
        $res = StoreService::getModel()
          ->saveAll($updateHouse);
        if ($res === false) {
          throw new \Exception('修改store_house失败');
        }
      }
      // 新增到store_house
      if ($insertHouse) {
        foreach ($insertHouse as $value) {
          $res1 = StoreService::getModel()->insertGetId($value);
          if ($res1 === false) {
            throw new \Exception('新增到store_house失败');
          }
          if (isset($insertOuter[$value['name']])) {
            $insertOuter[$value['name']]['store_id'] = $res1;
          }
        }
      }
      // 新增到outer_purchase
      if ($insertOuter) {
        $insertOuter = array_values($insertOuter);
        $res2 = self::getModel()->insertAll($insertOuter);
        if (!$res2) {
          throw new \Exception('新增到outer_purchase失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }

  }

}